import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login.vue'
import { useGlobalStore } from '../store/userInfo'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false // 不需要登录
    }
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('../components/Home.vue'),
    meta: {
      requiresAuth: true // 需要登录
    },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../components/Dashboard.vue')
      },
      {
        path: 'user-management',
        name: 'UserManagement',
        component: () => import('../views/UserManagement.vue')
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('../views/Statistics.vue')
      },
      {        path: 'article-management',        name: 'ArticleManagement',        component: () => import('../views/ArticleManagement.vue')      },      {        path: 'activity-management',        name: 'ActivityManagement',        component: () => import('../views/ActivityManagement.vue')      },      {        path: 'activity-apply-management',        name: 'ActivityApplyManagement',        component: () => import('../views/ActivityApplyManagement.vue')      },    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由拦截
router.beforeEach((to, from, next) => {
  const store = useGlobalStore()
  const token = store.token
  
  // 判断路由是否需要登录权限
  if (to.meta.requiresAuth) {
    if (token) {
      next() // 已登录，继续访问
    } else {
      next('/login') // 未登录，跳转到登录页
    }
  } else {
    // 不需要登录的路由，直接访问
    next()
  }
})

export default router